from fastapi import FastAPI,Request
from fastapi.responses import JSONResponse
from models.ai.config.settings import logger, TOKEN_KEY
from models.ai.utils.common import R
import time

app = FastAPI()
app.openapi_version = "3.0.0"

"""
    限流
    @author Charles
"""
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
    # limiter = RateLimiter(times=5, seconds=60)
        # await limiter(request)
    response = await call_next(request)
    return response

"""
    token校验
    @author Charles
"""
@app.middleware("http")
async def token_filter(request: Request, call_next):
    # 从请求头中获取token
    token = request.headers.get("Authorization")
    # 校验token
    if token != TOKEN_KEY:
        return JSONResponse(content=R.error("token错误"), status_code=401)
    # 如果token匹配，继续处理请求
    response = await call_next(request)
    return response

"""
    日志记录
    @author Charles
"""
@app.middleware("http")
async def log_filter(request: Request, call_next):
    # 记录请求开始时间
    start_time = time.time()
    try:
        # 调用下一个中间件或路由处理函数
        response = await call_next(request)
        logger.info(f"接口耗时:{time.time() - start_time}, uri={request.url.path}")
        return response
    except Exception as e:
        logger.error(e)
        return JSONResponse(R.error(str(e)), status_code=200)

"""
    全局异常处理
    @author Charles
"""
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    return JSONResponse(content=R.error(str(exc)), status_code=500)
